package com.xiaoma.tpo.webservice;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.domain.WdGroup;
import com.xiaoma.tpo.domain.WdScore;
import com.xiaoma.tpo.domain.WdUnlockProcess;
import com.xiaoma.tpo.domain.WdWord;
import com.xiaoma.tpo.dto.WdGroupVo;
import com.xiaoma.tpo.dto.WdPlanVo;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.service.WordService;
import com.xiaoma.tpo.utils.TPOUtils;

@Controller
@RequestMapping("/service/word")
public class WordWS {
    private static Logger LOG = LoggerFactory.getLogger(WordWS.class);
    
    @Autowired
    private WordService wordService;
    
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/plans", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findAllPlans(){
        List<WdPlanVo> wordPlans = wordService.findAllWordPlans();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("wordPlans", wordPlans);
        return result;
        
    }
    
    @RequestMapping(value = "/plans/{planId}/groups", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findGroupsByPlanId(@PathVariable Integer planId){
        List<WdGroupVo> wordGroups = wordService.findWordGroupsByPlanId(planId);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("wordGroups", wordGroups);
        return result;
        
    }
    
    @RequestMapping(value = "/groups/{groupId}/words", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findWordsByGroupId(@PathVariable Integer groupId){
        List<WdWord> words = wordService.findWordByGroupId(groupId);
        WdGroup group = wordService.findGroupById(groupId);
        Map<String, Object> result = new HashMap<String, Object>();
        if (group != null) {
            result.put("planId", group.getWdPlanId());
            result.put("groupId", group.getId());
        } else {
            result.put("planId", null);
            result.put("groupId", groupId);
            
        }
        result.put("words", words);
        return result;
        
    }
    
    @RequestMapping(value = "/unlockProcess", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUnlockProcess(@RequestHeader String token, Integer planId){
        Map<String, Object> result = new HashMap<String, Object>();
        
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        WdUnlockProcess unlockProcess = wordService.findProcessByPlanIdAndUserId(planId, user.getId());
        if (!TPOUtils.isAnonymous(user)) {//如果不是匿名用户，则更新访问时间
            userService.updateVisitTime(user);
        }
        result.put("unlockProcess", unlockProcess);
        return result;
        
    }
    
    @RequestMapping(value = "/unlockProcess", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submitUnlockProcess(@RequestHeader String token, @RequestBody Map<String, Object> map){
        Map<String, Object> result = new HashMap<String, Object>();
        Integer planId = (Integer)map.get("planId");
        Integer groupId = (Integer)map.get("groupId");
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        try {
            
            WdUnlockProcess unlockProcess = wordService.findProcessByPlanIdAndUserId(planId, user.getId());
            if (unlockProcess == null) {
                WdUnlockProcess newP = new WdUnlockProcess();
                newP.setUserId(user.getId());
                newP.setWdGroupId(groupId);
                newP.setWdPlanId(planId);
                wordService.saveUnlockProcess(newP);
            } else {
                if (unlockProcess.getWdGroupId() < groupId) {
                    unlockProcess.setWdGroupId(groupId);
                    unlockProcess.setWdPlanId(planId);
                    wordService.updateUnlockProcess(unlockProcess);
                }
            }
            if (!TPOUtils.isAnonymous(user)) {//如果不是匿名用户，则更新访问时间
                userService.updateVisitTime(user);
            }
            result.put("status", 1);
        } catch(Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }
        return result;
    }
    
    @RequestMapping(value = "/score", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submitScore(@RequestHeader String token, @RequestBody Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer planId = (Integer)map.get("planId");
        Integer groupId = (Integer)map.get("groupId");
        Integer score = (Integer)map.get("score");
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        try{
            WdScore wdScore = wordService.findScoreByPlanIdAndGroupIdAndUserId(planId, groupId, user.getId());
            if (wdScore == null) {
                wdScore = new WdScore();
                wdScore.setScore(score);
                wdScore.setUserId(user.getId());
                wdScore.setWdGroupId(groupId);
                wdScore.setWdPlanId(planId);
                wdScore.setCreatedAt(new Date());
                wordService.saveScore(wdScore);
            } else {
                wdScore.setScore(score);
                wordService.updateScore(wdScore);
            }
            int ranking = wordService.getRanking(wdScore, planId, groupId);
            if (!TPOUtils.isAnonymous(user)) {//如果不是匿名用户，则更新访问时间
                userService.updateVisitTime(user);
            }
            result.put("ranking", ranking);
        } catch(Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }
        return result;
    }
    
    @RequestMapping(value = "/score/ranking", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getRanking(@RequestHeader String token, Integer planId, Integer groupId) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        WdScore score = wordService.findScoreByPlanIdAndGroupIdAndUserId(planId, groupId, user.getId());
        if(score == null) {
            result.put("ranking", null);
        } else {
            int ranking = wordService.getRanking(score, planId, groupId);
            result.put("ranking", ranking);
        }
        if (!TPOUtils.isAnonymous(user)) {//如果不是匿名用户，则更新访问时间
            userService.updateVisitTime(user);
        }
        
        return result;
    }
    
    public static void main(String args[]) {
    }
}
